//
//  ShopCarVC.m
//  reSearchDemo
//
//  Created by 云库 on 15/9/28.
//  Copyright (c) 2015年 Kiwaro. All rights reserved.
//

#import "ShopCarVC.h"
#import "AFNetworking.h"
#import "UIView+Category.h"
#import "UIImageView+WebCache.h"
#import "GoodsCarList.h"
#import "MJExtension.h"
#import "ShopCarTableViewCell.h"
#import "BuyNowVC.h"
#import "MJRefresh.h"
@interface ShopCarVC ()<UITableViewDataSource,UITableViewDelegate> {
    BOOL isDataSource;
}

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dealsArr;/** 模型*/
@property (strong, nonatomic) UILabel *moneyLable;/** 总价*/
@property (nonatomic,assign) float price;/** 合计总价*/
/** 合计总价相关数组--//删除对象*/
@property (strong, nonatomic)NSMutableArray *deleteArray;

@end

@implementation ShopCarVC

/** 初始化*/
- (NSMutableArray *)dealsArr{
    if (!_dealsArr) {
        _dealsArr = [NSMutableArray array];
    }
    return _dealsArr;
}

/** 初始化*/
- (NSMutableArray *)deleteArray{
    if (!_deleteArray) {
        _deleteArray = [NSMutableArray array];
    }
    return _deleteArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.price=0.0;
    
    self.title = @"购物车";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(EditorBtnAction:)];
    
    //创建tableview
    [self createTableView];
    //加载数据源
    [self gotDataFromServer];
    //加载底部菜单
    [self createFootView];
    //下拉刷新
    [self setupDownRefresh];

}
#pragma mark --编辑按钮--
- (void)EditorBtnAction:(UIBarButtonItem *)sender {
    
    BOOL isEditing = self.tableView.isEditing;
    if (isEditing) {
        sender.title = @"编辑";
    }else {
        sender.title = @"取消";
    }
    
    [self.tableView setEditing:!isEditing animated:YES];
}
#pragma mark -
#pragma mark --下拉刷新--
/** 下拉刷新*/
- (void)setupDownRefresh
{
    // 1.添加刷新控件
    [self.tableView addHeaderWithTarget:self action:@selector(gotDataFromServer)];
    
    // 2.进入刷新状态(下拉刷新)
    [self.tableView headerBeginRefreshing];
    
}
#pragma mark - **************** 底部按钮视图
- (void)createFootView{
    UIView * bomBgView=[[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-50, self.view.frame.size.width, 50)];
    bomBgView.backgroundColor=[UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:0.9];
//    bomBgView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:bomBgView];
    UIButton * selectedBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    selectedBtn.frame=CGRectMake(10, 10, 30, 30);
    selectedBtn.tag = 2000;
    [selectedBtn setImage:[UIImage imageNamed:@"ic_01_n_"] forState:UIControlStateNormal];
    [selectedBtn setImage:[UIImage imageNamed:@"ic_01_h_"] forState:UIControlStateSelected];
    [selectedBtn addTarget:self action:@selector(AllSelectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [bomBgView addSubview:selectedBtn];
    UILabel * allSeleLab=[[UILabel alloc]initWithFrame:CGRectMake(selectedBtn.frame.size.width+selectedBtn.frame.origin.x+10, 10, 40, 30)];
    allSeleLab.text=@"全选";
    [bomBgView addSubview:allSeleLab];
    
    UIButton * accountBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    accountBtn.frame=CGRectMake(bomBgView.frame.size.width-100, 0, 100, 50);
    [accountBtn setTitle:@"结算" forState:UIControlStateNormal];
    accountBtn.tintColor=[UIColor whiteColor];
    accountBtn.backgroundColor=[UIColor redColor];
    [accountBtn addTarget:self action:@selector(accountBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bomBgView addSubview:accountBtn];
    
    UILabel * total=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width-220, 5, 50, 25)];
    total.text=@"合计:";
    [bomBgView addSubview:total];
    UILabel * moneyLab=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width-170, 5, 70, 25)];
    self.moneyLable = moneyLab;
    moneyLab.text=@"¥0.00";
    moneyLab.textAlignment = NSTextAlignmentCenter;
    moneyLab.textColor=[UIColor redColor];
    moneyLab.font=[UIFont systemFontOfSize:13];
    [bomBgView addSubview:moneyLab];
    UILabel * freightLab=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width-220, 30, 100, 20)];
    freightLab.text=@"不含运费";
    freightLab.font=[UIFont systemFontOfSize:15];
    [bomBgView addSubview:freightLab];

}
#pragma mark --全选按钮--
- (void)AllSelectBtnAction:(UIButton *)sender {
    
    __block CGFloat price = 0;
    if (sender.selected) {
        sender.selected = NO;
        [self.dealsArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            GoodsCarList *goods = obj;
            UIImageView *image=(UIImageView*)[self.tableView viewWithTag:100+idx];
            [image setImage:[UIImage imageNamed:@"ic_01_n_"]];
            goods.isSelect = NO;
            self.moneyLable.text = @"￥0.00";
        }];
    }else {
        sender.selected = YES;
        [self.dealsArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            GoodsCarList *goods = obj;
            UIImageView *image=(UIImageView*)[self.tableView viewWithTag:100+idx];
            [image setImage:[UIImage imageNamed:@"ic_01_h_"]];
            goods.isSelect = YES;
            
            if (goods.isSelect) {
                price += goods.money;
                self.moneyLable.text=[NSString stringWithFormat:@"￥%.2f",price];
            }
        }];
        
    }
}
#pragma mark --结算按钮--
- (void)accountBtnClick:(UIButton *)button{
    NSMutableArray *data = [NSMutableArray array];
    for (int i = 0; i<self.dealsArr.count; i++) {
        GoodsCarList *goods = self.dealsArr[i];
        if (goods.isSelect) {
            [data addObject:goods];
        }
    }
    if (!data.count) {
        [self showText:@"请选择商品"];
        return;
    }
    BuyNowVC *buyVc = [[BuyNowVC alloc] init];
    buyVc.model = data;
    [self pushViewController:buyVc];
}

#pragma mark - **************** tableView
- (void)createTableView{
    self.tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 50)];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.backgroundColor = [UIColor clearColor];
    _tableView.allowsSelectionDuringEditing = YES; //编辑状态下可以选中
    _tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.tableView];
}

#pragma mark - **************** 获取数据
- (void)gotDataFromServer{
    self.HUD.labelText = @"请稍后";
    [self.HUD show:YES];
    DLog(@"self.hud = %@",self.HUD);
    //获取购物车列表
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    NSString *path = [NSString stringWithFormat:@"%@%@",SHOPER,@"html/acar/goodlist?huiYuan_id=83"];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        DLog(@"responseObject = %@",responseObject);
        NSString *status = responseObject[@"status"];
        if (![status intValue]) {
            isDataSource = YES;
            NSArray *array = [GoodsCarList objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.dealsArr removeAllObjects];
            [self.dealsArr addObjectsFromArray:array];
            [self.tableView reloadData];
            [self.HUD hide:YES];
            self.title = [NSString stringWithFormat:@"购物车(%lu)",(unsigned long)array.count];
            
        }else {
            self.HUD.labelText = @"暂无商品";
            [self.HUD hide:YES afterDelay:0.5];
            isDataSource = NO;
        }
        // 结束刷新刷新
        [self.tableView headerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        self.HUD.labelText = @"加载失败";
        [self.HUD hide:YES afterDelay:1.0];
        isDataSource = NO;
        // 结束刷新刷新
        [self.tableView headerEndRefreshing];
    }];

}
#pragma mark - **************** 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dealsArr.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"ShopCarTableViewCell";
    ShopCarTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell = [[[NSBundle mainBundle]loadNibNamed:@"ShopCarTableViewCell" owner:self options:nil]lastObject];
        cell.tag=1000+indexPath.row;
        cell.smallImg.tag = 100+indexPath.row;
    }
    
    GoodsCarList * deal = self.dealsArr[indexPath.row];
    cell.deal = deal;
    cell.block = ^(NSString *cars_box_id,int num) {
        self.HUD.labelText = @"请稍后";
        [self.HUD show:YES];
        //修改购物车数量
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSString *path = [NSString stringWithFormat:@"%@%@",SHOPER,@"html/acar/modify"];
        NSDictionary *dic = @{@"cars_box_id":cars_box_id,@"num":[NSString stringWithFormat:@"%d",num]};
        [manager GET:path parameters:dic success:^(AFHTTPRequestOperation * operation, id obj) {
            NSString *status = obj[@"status"];
            if (![status intValue]) {
                [self.HUD hide:YES];
            }else {
                self.HUD.labelText = @"修改失败";
                [self.HUD hide:YES afterDelay:1.0];
            }
        } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
            self.HUD.labelText = @"修改失败";
            [self.HUD hide:YES afterDelay:1.0];
            DLog(@"error = %@",error);
        }];
    };
    
    
    return cell;

}
#pragma mark --cell点击事件--
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIImageView*btn=(UIImageView*)[tableView viewWithTag:100+indexPath.row];
    
    NSIndexPath*path=[NSIndexPath indexPathForRow:btn.tag-100 inSection:0];
//    ShopCarTableViewCell *cell = (ShopCarTableViewCell*)[tableView viewWithTag:indexPath.row+1000];
    GoodsCarList *goodsCarlist = self.dealsArr[indexPath.row];
   //改变当前选中状态
    if (!goodsCarlist.isSelect)
    {
        btn.image = [UIImage imageNamed:@"ic_01_h_.png"];
        [self.deleteArray addObject:path];
        goodsCarlist.isSelect = YES;
    }else{
        btn.image = [UIImage imageNamed:@"ic_01_n_.png"];
        [self.deleteArray removeObject:path];
        goodsCarlist.isSelect = NO;
    }
    
    //选中状态,改变合计金额
    __block float price = 0;
    __block int number = 0;
    [self.dealsArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        GoodsCarList *goods = obj;
        if (goods.isSelect) {
            number++;
            price += goods.money;
            self.moneyLable.text=[NSString stringWithFormat:@"￥%.2f",price];
            if (number == self.dealsArr.count) {
                UIButton *btn = (UIButton *)[self.view viewWithTag:2000];
                btn.selected = YES;
            }else {
                UIButton *btn = (UIButton *)[self.view viewWithTag:2000];
                btn.selected = NO;
            }
        }
    }];
}
#pragma mark --cell的高度--
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
#pragma mark --头视图--
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView;
    if (!isDataSource) {
        headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_tableView.frame), CGRectGetHeight(_tableView.frame))];
        headView.backgroundColor = [UIColor lightGrayColor];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        label.center = headView.center;
        label.text = @"无内容!";
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:25];
        [headView addSubview:label];
        
        return headView;
    }else {
        return nil;
    }
}
#pragma mark --头视图高度--
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (!isDataSource) {
        return CGRectGetHeight(self.view.frame)-50;
    }else {
        return 0;
    }
}
#pragma mark --// 指定哪一行可以编辑 哪行不能编辑 --
- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
#pragma mark --// 设置 哪一行的编辑按钮 状态 指定编辑样式 --
- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
#pragma mark --判断点击按钮的样式 来去做添加 或删除--
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    GoodsCarList *goods = self.dealsArr[indexPath.row];
    DLog(@"goods.name = %@",goods.shopname);
    DLog(@"goods.cartGoodsId = %@",goods.cars_box_id);
    DLog(@"goods.good_id = %d",goods.good_id);
    // 删除的操作
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        self.HUD.labelText = @"请稍后";
        [self.HUD show:YES];
        //删除购物车商品
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSString *path = [NSString stringWithFormat:@"%@%@",SHOPER,@"widget.html"];
        NSDictionary *dic = @{@"widget":@"carsWidget",@"dataType":@"json",@"action":@"del",@"carInfo":[NSString stringWithFormat:@"%d%@",goods.good_id,@":::|"],@"huiYuan_id":@"83"};
        [manager GET:path parameters:dic success:^(AFHTTPRequestOperation * Operation, id obj) {
            [self.HUD hide:YES];
            DLog(@"obj = %@",obj);
            NSString *status = obj[@"status"];
            if (![status intValue]) {
                [self.HUD hide:YES];
                [self.dealsArr removeObjectAtIndex:indexPath.row];
                
                NSArray *indexPaths = @[indexPath]; // 构建索引处的行数的数组
                // 删除索引的方法 后面是动画样式
                [_tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:(UITableViewRowAnimationLeft)];
                [self.tableView setEditing:NO animated:YES];
                self.navigationItem.rightBarButtonItem.title = @"编辑";
                if (!self.dealsArr) {
                    isDataSource = NO;
                    [self.tableView reloadData];
                }
            }else {
                self.HUD.labelText = @"修改失败";
                [self.HUD hide:YES afterDelay:1.0];
            }
            
        } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
            self.HUD.labelText = @"加载失败";
            [self.HUD hide:YES afterDelay:1.0];
            DLog(@"error = %@",error);
        }];
        
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}





@end
